""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
set nocompatible              " be iMproved, required
filetype off                  " required
"设置Vundle的运行路径并初始化
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" Vundle安装位置与插件路径不同时，需要Vundle插件的路径
"call vundle#begin('~/some/path/here')
"------------------要安装的插件不能写在此行前！------------------

Plugin 'Yggdroot/indentLine'

Plugin  'voldikss/vim-floaterm'
let g:floaterm_wintype = 'split'
let g:floaterm_height = 0.3
let g:floaterm_keymap_new    = '<C-j>'

"An always-on highlight for a unique character
Plugin 'unblevable/quick-scope'

Plugin 'luochen1990/rainbow'
let g:rainbow_active = 1

Plugin 'mhinz/vim-startify'

"注释插件
Plugin 'preservim/nerdcommenter'
"\cc 注释当前行
"\cu 取消注释
"\cs 以”性感”的方式注释
"\cA 在当前行尾添加注释符，并进入Insert模式
"2,cu 光标以下count行取消注释
let g:NERDSpaceDelims=1

Plugin 'Yggdroot/LeaderF'
let g:Lf_ShowDevIcons = 0
let g:Lf_ShortcutF = '<C-P>'
let g:Lf_HideHelp = 1
let g:Lf_UseCache = 0
let g:Lf_UseVersionControlTool = 0
let g:Lf_IgnoreCurrentBufferName = 1
noremap <leader>fb :<C-U><C-R>=printf("Leaderf  --popup buffer %s", "")<CR><CR>
noremap <leader>ff :<C-U><C-R>=printf("Leaderf  --popup function %s", "")<CR><CR>
noremap <leader>ft :<C-U><C-R>=printf("Leaderf  --popup tag %s", "")<CR><CR>

Plugin 'rust-lang/rust.vim'

"Vundle对自己的调用，不可删去
Plugin 'VundleVim/Vundle.vim'
"需要安装的插件应写在调用的vundle#begin和vundle#end之间
"插件托管在Github上，写在下方，只写作者名/项目名就行了
"插件来自vim-scripts(官方)，写插件名就行了
"Git仓库不在Github上，需要提供完整的链接
 
Plugin 'majutsushi/tagbar'
" s键切换排序方式
"autocmd BufReadPost *.cpp,*.c,*.h,*.hpp,*.cc,*.cxx call tagbar#autoopen() "如果是c语言的程序的话，tagbar自动开启
let g:tagbar_ctags_bin='ctags' "ctags程序的路径 "
let g:tagbar_width=40 "窗口宽度的设置 
let g:tagbar_left=1
let g:tagbar_autopreview=0
let g:tagbar_autofocus = 1
map <F3> :Tagbar<CR> 

Plugin 'neoclide/coc.nvim', {'branch': 'release'}
":CocInstall coc-snippets
":CocUninstall coc-css
":CocList extensions
"vim -c 'CocUpdateSync|q'  //update extensions
let g:coc_global_extensions =['coc-snippets', 'coc-clangd', 'coc-pyright']

"显示mark
Plugin'kshenoy/vim-signature'

"任意跳转工具
Plugin 'easymotion/vim-easymotion'
nmap ss <Plug>(easymotion-s2)

"设置主题
Plugin 'sonph/onehalf'
set cursorline
colorscheme onehalflight
" let g:airline_theme='onehalflight'
" lightline
" let g:lightline = { 'colorscheme': 'onehalfdark' }

Plugin 'vim-airline/vim-airline-themes'
" let g:airline_theme='simple'
" let g:airline_theme='papercolor'
 " let g:airline_theme="solarized"
 " let g:airline_solarized_bg='dark'

Plugin 'vim-airline/vim-airline'
 let g:airline_extensions = ['branch', 'tagbar', 'tabline']
 let g:airline#extensions#tabline#formatter = 'unique_tail'
 let g:airline#extensions#tabline#buffer_nr_show = 1
 let g:airline_powerline_fonts = 1
 let g:airline#extensions#tabline#enabled = 1
 let g:airline#extensions#bookmark#enabled = 1
 let g:airline#extensions#default#layout = [
      \ [ 'a', 'b', 'c' ],
      \ [ 'y', 'z']
      \ ]

"文档生成
Plugin 'kkoomen/vim-doge'
" npm i
" npm run build
" or :call doge#install()
let g:doge_mapping = '<leader>dc'
 
"翻译 https://github.com/ianva/vim-youdao-translater
Plugin  'https://github.com/ianva/vim-youdao-translater.git'
vnoremap <silent> <C-X> :<C-u>Ydv<CR>
nnoremap <silent> <C-X> :<C-u>Ydc<CR>
noremap <leader>yd :<C-u>Yde<CR>
" Plugin 'L9'

 " Bundle 'fholgado/minibufexpl.vim'
 " let g:miniBufExplMapWindowNavVim = 1
 " let g:miniBufExplMapWindowNavArrows = 1
 " let g:miniBufExplMapCTabSwitchBufs = 1
 " let g:miniBufExplModSelTarget = 1
 " let g:miniBufExplMoreThanOne=0
 " let g:miniBufExplAutoStart = 1
" MiniBufExpl Colors
" hi MBENormal               guifg=#808080 guibg=fg
  " hi MBEChanged              guifg=#CD5907 guibg=fg
" hi MBEVisibleNormal        guifg=#5DC2D6 guibg=fg
" hi MBEVisibleChanged       guifg=#F1266F guibg=fg
" hi MBEVisibleActiveNormal  guifg=#A6DB29 guibg=fg
" hi MBEVisibleActiveChanged guifg=#F1266F guibg=fg
"
 " let g:miniBufExplorerDebugMode  = 2
 " let g:miniBufExplorerDebugLevel = 8


" Track the engine.
Plugin 'SirVer/ultisnips'

" Snippets are separated from the engine. Add this if you want them:
Plugin 'honza/vim-snippets'
" Trigger configuration. You need to change this to something other than <tab> if you use one of the following:
" - https://github.com/Valloric/YouCompleteMe
" - https://github.com/nvim-lua/completion-nvim
let g:UltiSnipsExpandTrigger="<tab>"
let g:UltiSnipsJumpForwardTrigger="<c-b>"
let g:UltiSnipsJumpBackwardTrigger="<c-z>"

" If you want :UltiSnipsEdit to split your window.
let g:UltiSnipsEditSplit="vertical"

"本地的插件需要提供文件路径
" Plugin 'file:///home/gmarik/path/to/plugin'
"一定要确保插件就在提供路径的文件夹中(没有子文件夹，直接在这层目录下)
"运行时目录的路径
"Plugin 'rstacruz/sparkup', {'rtp': 'vim/'}
"避免插件间的命名冲突
"Plugin 'ascenator/L9', {'name': 'newL9'}
"------------------要安装的插件不能写在此行后！------------------
call vundle#end()            " required
filetype plugin indent on    " required
"要忽略插件缩进更改，请改用：
"filetype plugin on
"
" 安装插件的相关指令
":PluginList			- 列出已安装插件
":PluginInstall			- 安装新添加的插件;添加`!`或使用`:PluginUpdate`来更新已安装插件
":PluginSearch xxx		- 寻找名字带有xxx的插件;添加`!`刷新本地缓存
":PluginClean			- 删除已经从列表移除的插件;添加`!`静默卸载
":h						- 帮助和说明文档 
"Vundle的设置到此为止了
"
set ruler  "显示标尺 

"disable modifyOtherKeys mode
let &t_TI = ""
let &t_TE = ""
"设置光标样式
let &t_SI = "\e[6 q"
let &t_SR = "\e[4 q"
let &t_EI = "\e[2 q"

set nu

" 为C程序提供自动缩进
set smartindent 

" 设定 tab 长度为 4  
set tabstop=4 
set shiftwidth=4
" 展开tab为空格
set expandtab
set autoindent

" BackSpace可以一次删除掉4个空格
set softtabstop=4

" 搜索时高亮显示被找到的文本
set hlsearch

set langmenu=zh_CN.UTF-8

set ambiwidth=double

" enable true colors
if exists('+termguicolors')
  let &t_8f = "\<Esc>[38;2;%lu;%lu;%lum"
  let &t_8b = "\<Esc>[48;2;%lu;%lu;%lum"
  set termguicolors
endif

"显示括号配对情况
"set showmatch

" 自动语法高亮
syntax on

set complete=.
set fdm=syntax
set foldlevel=4

set rtp+=~/.vim/bundle/CompleteParameter.vim

"
"自动保存折叠
"au BufWinLeave * silent mkview
"au BufWinEnter * silent loadview

set fileformats=unix,dos

set listchars=tab:>-,trail:-
set backspace=indent,eol,start
set mouse=

"split navigations
nnoremap <C-J> <C-W><C-J>
nnoremap <C-K> <C-W><C-K>
nnoremap <C-L> <C-W><C-L>
nnoremap <C-H> <C-W><C-H>

map <F4> :cs find 

if has("cscope")
    set csprg=/usr/bin/cscope
    set csto=0
    set cst
    set nocsverb
    " add any database in current directory

    if filereadable("cscope.out")
            cs add cscope.out
            " else add database pointed to by environment
    elseif $CSCOPE_DB != ""
            cs add $CSCOPE_DB
    endif

    set csverb
endif

map <F5> :call CompileRunGcc()<CR>
func! CompileRunGcc()
    exec "w" 
    if &filetype == 'c' 
        exec '!g++ % -o %<'
        exec '!time ./%<'
    elseif &filetype == 'cpp'
        exec '!g++ % -o %<'
        exec '!time ./%<'
    elseif &filetype == 'python'
        exec '!time python %'
    elseif &filetype == 'sh'
        :!time bash %
    endif                                                                              
endfunc 

":n,m bdelete 删除n~m buffer
" 删除除当前以外的buffer
fun! DeleteAllBuffersInWindow ()
	let s :curWinNr   =  winnr ()
	if  winbufnr ( s :curWinNr )   ==   1
		ret
	endif
	let s :curBufNr   =  bufnr ( " % " )
	exe  " bn "
	let s :nextBufNr   =  bufnr ( " % " )
	while s :nextBufNr  ! =  s :curBufNr
		exe  " bn "
		exe  " bdel  " . s :nextBufNr
		let s :nextBufNr   =  bufnr ( " % " )
	endwhile
endfun

map <C-Del> bd:call  DeleteAllBuffersInWindow ()

cnoreabbrev <expr> W ((getcmdtype() is# ':' && getcmdline() is# 'W')?('w'):('W'))
" Set internal encoding of vim, not needed on neovim, since coc.nvim using some
" unicode characters in the file autoload/float.vim
set encoding=utf-8

" TextEdit might fail if hidden is not set.
set hidden

" Some servers have issues with backup files, see #649.
set nobackup
set nowritebackup

" Give more space for displaying messages.
set cmdheight=1

" Having longer updatetime (default is 4000 ms = 4 s) leads to noticeable
" delays and poor user experience.
set updatetime=300

" Don't pass messages to |ins-completion-menu|.
set shortmess+=c

" Always show the signcolumn, otherwise it would shift the text each time
" diagnostics appear/become resolved.
if has("nvim-0.5.0") || has("patch-8.1.1564")
  " Recently vim can merge signcolumn and number column into one
  set signcolumn=number
else
  set signcolumn=yes
endif

" large file
let g:LargeFile = 1024 * 1024 * 6
let g:MedFile = 1024 * 100 * 6
augroup LargeFile
	autocmd BufReadPre * let f=getfsize(expand("<afile>")) | if f > g:LargeFile || f == -2 | call LargeFile() | elseif f > g:MedFile | call MedFile() |endif
augroup END

function MedFile()
set fdm=indent
autocmd VimEnter *  echo "The file is larger than " . (g:MedFile / 1024 ) . " Kib, so some options are changed (see .vimrc for details)."
endfunction

function LargeFile()
call MedFile()
" no syntax highlighting etc
set eventignore+=FileType
" save memory when other file is viewed
setlocal bufhidden=unload
" is read-only (write with :w new_filename)
setlocal buftype=nowrite
" no undo possible
setlocal undolevels=-1

syntax off

" display message
autocmd VimEnter *  echo "The file is larger than " . (g:LargeFile / 1024 / 1024) . " MB, so some options are changed (see .vimrc for details)."
endfunction

" -------------------------------------------------------------------------------------------------
" coc.nvim default settings
" -------------------------------------------------------------------------------------------------
" Use tab for trigger completion with characters ahead and navigate.
" NOTE: Use command ':verbose imap <tab>' to make sure tab is not mapped by
" other plugin before putting this into your config.
" Use <C-l> for trigger snippet expand.
inoremap <silent><expr> <TAB>
      \ pumvisible() ? coc#_select_confirm() :
      \ coc#expandableOrJumpable() ? "\<C-r>=coc#rpc#request('doKeymap', ['snippets-expand-jump',''])\<CR>" :
      \ <SID>check_back_space() ? "\<TAB>" :
      \ coc#refresh()

function! s:check_back_space() abort
  let col = col('.') - 1
  return !col || getline('.')[col - 1]  =~# '\s'
endfunction

set tagfunc=CocTagFunc

let g:coc_snippet_next = '<tab>'

" Use <c-space> to trigger completion.
if has('nvim')
  inoremap <silent><expr> <c-space> coc#refresh()
else
  inoremap <silent><expr> <c-@> coc#refresh()
endif

" Make <CR> auto-select the first completion item and notify coc.nvim to
" format on enter, <cr> could be remapped by other vim plugin
inoremap <silent><expr> <cr> pumvisible() ? coc#_select_confirm()
                              \: "\<C-g>u\<CR>\<c-r>=coc#on_enter()\<CR>"

" Use `[g` and `]g` to navigate diagnostics
" Use `:CocDiagnostics` to get all diagnostics of current buffer in location list.
nmap <silent> [g <Plug>(coc-diagnostic-prev)
nmap <silent> ]g <Plug>(coc-diagnostic-next)

" GoTo code navigation.
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gy <Plug>(coc-type-definition)
nmap <silent> gi <Plug>(coc-implementation)
nmap <silent> gr <Plug>(coc-references)

" Use K to show documentation in preview window.
nnoremap <silent> K :call <SID>show_documentation()<CR>

function! s:show_documentation()
  if (index(['vim','help'], &filetype) >= 0)
    execute 'h '.expand('<cword>')
  elseif (coc#rpc#ready())
    call CocActionAsync('doHover')
  else
    execute '!' . &keywordprg . " " . expand('<cword>')
  endif
endfunction

" Highlight the symbol and its references when holding the cursor.
" autocmd CursorHold * silent call CocActionAsync('highlight')

" Symbol renaming.
nmap <leader>rn <Plug>(coc-rename)

" Formatting selected code.
xmap <leader>f  <Plug>(coc-format-selected)
nmap <leader>f  <Plug>(coc-format-selected)

augroup mygroup
  autocmd!
  " Setup formatexpr specified filetype(s).
  autocmd FileType typescript,json setl formatexpr=CocAction('formatSelected')
  " Update signature help on jump placeholder.
  autocmd User CocJumpPlaceholder call CocActionAsync('showSignatureHelp')
augroup end

" Applying codeAction to the selected region.
" Example: `<leader>aap` for current paragraph
xmap <leader>a  <Plug>(coc-codeaction-selected)
nmap <leader>a  <Plug>(coc-codeaction-selected)

" Remap keys for applying codeAction to the current buffer.
nmap <leader>ac  <Plug>(coc-codeaction)
" Apply AutoFix to problem on the current line.
nmap <leader>qf  <Plug>(coc-fix-current)

" Map function and class text objects
" NOTE: Requires 'textDocument.documentSymbol' support from the language server.
xmap if <Plug>(coc-funcobj-i)
omap if <Plug>(coc-funcobj-i)
xmap af <Plug>(coc-funcobj-a)
omap af <Plug>(coc-funcobj-a)
xmap ic <Plug>(coc-classobj-i)
omap ic <Plug>(coc-classobj-i)
xmap ac <Plug>(coc-classobj-a)
omap ac <Plug>(coc-classobj-a)

" Remap <C-f> and <C-b> for scroll float windows/popups.
if has('nvim-0.4.0') || has('patch-8.2.0750')
  nnoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? coc#float#scroll(1) : "\<C-f>"
  nnoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? coc#float#scroll(0) : "\<C-b>"
  inoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? "\<c-r>=coc#float#scroll(1)\<cr>" : "\<Right>"
  inoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? "\<c-r>=coc#float#scroll(0)\<cr>" : "\<Left>"
  vnoremap <silent><nowait><expr> <C-f> coc#float#has_scroll() ? coc#float#scroll(1) : "\<C-f>"
  vnoremap <silent><nowait><expr> <C-b> coc#float#has_scroll() ? coc#float#scroll(0) : "\<C-b>"
endif

" Use CTRL-S for selections ranges.
" Requires 'textDocument/selectionRange' support of language server.
nmap <silent> <C-s> <Plug>(coc-range-select)
xmap <silent> <C-s> <Plug>(coc-range-select)

" Add `:Format` command to format current buffer.
command! -nargs=0 Format :call CocAction('format')

" Add `:Fold` command to fold current buffer.
command! -nargs=? Fold :call     CocAction('fold', <f-args>)

" Add `:OR` command for organize imports of the current buffer.
command! -nargs=0 OR   :call     CocAction('runCommand', 'editor.action.organizeImport')

" Add (Neo)Vim's native statusline support.
" NOTE: Please see `:h coc-status` for integrations with external plugins that
" provide custom statusline: lightline.vim, vim-airline.
" set statusline^=%{coc#status()}%{get(b:,'coc_current_function','')}

" Mappings for CoCList
" Show all diagnostics.
nnoremap <silent><nowait> <space>a  :<C-u>CocList diagnostics<cr>
" Manage extensions.
nnoremap <silent><nowait> <space>e  :<C-u>CocList extensions<cr>
" Show commands.
nnoremap <silent><nowait> <space>c  :<C-u>CocList commands<cr>
" Find symbol of current document.
nnoremap <silent><nowait> <space>o  :<C-u>CocList outline<cr>
" Search workspace symbols.
nnoremap <silent><nowait> <space>s  :<C-u>CocList -I symbols<cr>
" Do default action for next item.
nnoremap <silent><nowait> <space>j  :<C-u>CocNext<CR>
" Do default action for previous item.
nnoremap <silent><nowait> <space>k  :<C-u>CocPrev<CR>
" Resume latest coc list.
nnoremap <silent><nowait> <space>p  :<C-u>CocListResume<CR>

inoremap <expr> <cr> coc#pum#visible() ? coc#_select_confirm() : "\<CR>"
" 设置补全提示颜色
hi CocSearch ctermfg=102 guifg=#7a9d25
hi CocMenuSel ctermbg=19 guibg=#BBFFFF
